package com.example.myspringai.voice;

import okhttp3.*;

import javax.net.ssl.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.cert.CertificateException;
import java.util.concurrent.TimeUnit;

public class IntellaMe {

    private static final int CHUNK_SIZE = 1024 * 1024; // 1 MB

    public static void main(String[] args) throws Exception {
        new IntellaMe().uploadFileInChunks(
                "https://api.intella-voice.com/api/accounts/be216b3f-c48c-4b5f-b455-21635fb36f41/Requests?folderId=yourFolderId",
                "jbJF01a/7EW7vD3fk3AQ/Q==",
                "C:\\Users\\Administrator\\Desktop\\standard-dataset\\standard_darija\\darija_01\\darija_01.mp3"
        );
    }

    public void uploadFileInChunks(String urlString, String apiToken, String filePath) throws Exception {
        File file = new File(filePath);
        if (!file.exists() || !file.canRead()) {
            System.err.println("File not found or cannot be read: " + filePath);
            return;
        }

        OkHttpClient client = createUnsafeOkHttpClient();

        try (FileInputStream fis = new FileInputStream(file)) {
            byte[] buffer = new byte[CHUNK_SIZE];
            int bytesRead;
            int partNumber = 1;

            while ((bytesRead = fis.read(buffer)) != -1) {
                RequestBody fileBody = RequestBody.create(MediaType.parse("application/octet-stream"), buffer, 0, bytesRead);
                RequestBody requestBody = new MultipartBody.Builder()
                        .setType(MultipartBody.FORM)
                        .addFormDataPart("file", file.getName(), fileBody)
                        .addFormDataPart("fileName", "example")
                        .addFormDataPart("timestamp", "10")
                        .addFormDataPart("noOfSpeakers", "1")
                        .build();

                Request request = new Request.Builder()
                        .url(urlString)
                        .post(requestBody)
                        .addHeader("x-ApiToken", apiToken)
                        .build();

                try (Response response = client.newCall(request).execute()) {
                    if (!response.isSuccessful()) {
                        System.err.println("Chunk upload failed: " + response);
                        return;
                    }
                    System.out.println("Chunk " + partNumber + " uploaded successfully.");
                    partNumber++;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private OkHttpClient createUnsafeOkHttpClient() {
        try {
            // Create a trust manager that does not validate certificate chains
            final TrustManager[] trustAllCerts = new TrustManager[]{
                    new X509TrustManager() {
                        @Override
                        public void checkClientTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public void checkServerTrusted(java.security.cert.X509Certificate[] chain, String authType) throws CertificateException {
                        }

                        @Override
                        public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                            return new java.security.cert.X509Certificate[]{};
                        }
                    }
            };

            // Install the all-trusting trust manager
            final SSLContext sslContext = SSLContext.getInstance("SSL");
            sslContext.init(null, trustAllCerts, new java.security.SecureRandom());
            // Create an ssl socket factory with our all-trusting manager
            final SSLSocketFactory sslSocketFactory = sslContext.getSocketFactory();

            OkHttpClient.Builder builder = new OkHttpClient.Builder();
            builder.sslSocketFactory(sslSocketFactory, (X509TrustManager) trustAllCerts[0]);
            builder.hostnameVerifier((hostname, session) -> true);

            return builder
                    .connectTimeout(10, TimeUnit.SECONDS)
                    .readTimeout(10, TimeUnit.SECONDS)
                    .writeTimeout(10, TimeUnit.SECONDS)
                    .build();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}
